package com.nbsaas.boot.controller.data.utils;

import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by ada on 2017/7/29.
 */
public class MapUtils {

  /**
   * 获取一个按照key排序的map
   *
   */
  public static Map<String, String> getSortMap() {
      // 升序排序
      // 升序排序
      return new TreeMap<>(
              String::compareTo);
  }

  /**
   * 拼接url参数
   *
   */
  public static String params(Map<String, String> map) {
    StringBuilder buffer = new StringBuilder();
    Set<String> keySet = map.keySet();
    Iterator<String> iter = keySet.iterator();
    if (iter.hasNext()) {
      String key = iter.next();
      buffer.append(key);
      buffer.append("=");
      buffer.append(map.get(key));
    }
    while (iter.hasNext()) {
      String key = iter.next();
      buffer.append("&");
      buffer.append(key);
      buffer.append("=");
      buffer.append(map.get(key));
    }
    return buffer.toString();
  }

  public static String sign(Map<String, Object> params) {
    TreeMap<String, Object> sorted = new TreeMap<>(params);
    
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, Object> entry : sorted.entrySet()) {
      if (entry.getValue() == null || "".equals(entry.getValue())) continue;
      sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
    }
    if (sb.length() > 0) sb.setLength(sb.length() - 1);
    String signStr = sb.toString();
    String hash = DigestUtils.md5DigestAsHex(signStr.getBytes(StandardCharsets.UTF_8));
    return "temp_bsyc_" + hash;
  }

  public static void main(String[] args) {
    Map<String, Object> map = new TreeMap<>();
    //map.put("a", "1");
    //map.put("b", "2");
    System.out.println(sign(map));
  }

}
